import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

import sys
sys.path.append("../")
from controller.StockBaseController import *

class PltImage:

    def run(self, code, start_day, end_day):
        try:
            self.subrun(code,start_day,end_day)
        except:
            pass

    def subrun(self,code,start_day,end_day):
        stock = StockBaseController()
        df_all = stock.get_data(code,start_day,end_day)
        x = df_all.index
        y1 = df_all['close']

        y2 = df_all["close"]
        y3 = df_all["close"]

        text1 = []
        for i in range(len(x)):
            str_info = 'close: ' + str(df_all['close'][i]) + '\n' + 'ma18: ' + str(df_all['ma18'][i]) + '\n' + '日期: ' + str(df_all.index[i])
            text1.append(str_info)
        text2 = []
        for i in range(len(x)):
            text2.append(" ")

        # ---------- 画图 ----------
        fig,ax = plt.subplots(figsize=(20, 6))

        # 折线图
        ax.plot(x, y1, color='royalblue', lw=2.5, label='data')
        ax.plot(df_all["ma18"], label='ma18')
        ax.plot(df_all["ma10"], label='ma10')
        # 折线图上的散点
        ax.scatter(x, y2, c='darkgreen', label='买')
        ax.scatter(x, y3, c='firebrick', label='卖')

        # 一些小设置
        # 设置 x 轴显示密度
        tick_spacing = 8
        ax.xaxis.set_major_locator(ticker.MultipleLocator(tick_spacing))
        # 设置 x 坐标轴标签的显示内容和大小
        plt.xlabel('时间', fontsize=16)
        # 设置 x 坐标轴刻度的旋转方向和大小
        plt.xticks(rotation=90, fontsize=16)
        # 设置 y 坐标轴刻度大小
        plt.yticks(fontsize=18)
        # 坐标轴中文显示
        plt.rcParams['font.sans-serif'] = ['SimHei']
        # 调整图的位置
        plt.subplots_adjust(top=0.9, bottom=0.22)

        # po_annotation1 为 ‘买’ 时需要显示的标注信息
        # 该 list 内部存放多个子 list，每个子 list 为 [标注点的坐标, 标注]
        po_annotation1 = []
        for i in range(len(x)):
            # 标注点的坐标
            point_x = x[i]
            point_y = y2[i]
            point, = plt.plot(point_x, point_y, c='darkgreen')
            # 标注框偏移量
            offset1 = 80
            offset2 = 80
            # 标注框
            bbox1 = dict(boxstyle="round", fc='lightgreen', alpha=0.6)
            # 标注箭头
            arrowprops1 = dict(arrowstyle="->", connectionstyle="arc3,rad=0.")
            # 标注
            annotation = plt.annotate(text1[i], xy=(x[i], y2[i]), xytext=(-offset1, offset2), textcoords='offset points',
                                      bbox=bbox1, arrowprops=arrowprops1, size=15)
            # 默认鼠标未指向时不显示标注信息
            annotation.set_visible(False)
            po_annotation1.append([point, annotation])

        po_annotation2 = []
        for i in range(len(x)):
            # 标注点的坐标：
            point_x = x[i]
            point_y = y3[i]
            point, = plt.plot(point_x, point_y, c='firebrick')
            # 标注框偏移量
            offset1 = 30
            offset2 = 80
            # 标注框
            bbox2 = dict(boxstyle="round", fc='salmon', alpha=0.6)
            # 标注箭头
            arrowprops2 = dict(arrowstyle="->", connectionstyle="arc3,rad=0.")
            # 标注
            annotation = plt.annotate(text2[i], xy=(x[i], y3[i]), xytext=(-offset1, offset2), textcoords='offset points',
                                      bbox=bbox2, arrowprops=arrowprops2, size=15)
            # 默认鼠标未指向时不显示标注信息
            annotation.set_visible(False)
            po_annotation2.append([point, annotation])

        # 定义鼠标响应函数
        def on_move(event):
            visibility_changed = False
            for point, annotation in po_annotation1:
                should_be_visible = (point.contains(event)[0] == True)

                if should_be_visible != annotation.get_visible():
                    visibility_changed = True
                    annotation.set_visible(should_be_visible)

            for point, annotation in po_annotation2:
                should_be_visible = (point.contains(event)[0] == True)

                if should_be_visible != annotation.get_visible():
                    visibility_changed = True
                    annotation.set_visible(should_be_visible)

            if visibility_changed:
                plt.draw()
        # 鼠标移动事件
        on_move_id = fig.canvas.mpl_connect('motion_notify_event', on_move)
        '''
        fig1, ax2 = plt.subplots(figsize=(20, 2))
        ax2.plot(df_all["v18"], label='v18')
        ax2.plot(df_all["v10"], label='v10')
        ax2.plot(df_all["v5"], label='v5')
        ax2.bar(df_all.index, df_all["volume"], width=0.5)
        ax2.set_ylabel('Volume')
        # 设置 x 坐标轴标签的显示内容和大小
        plt.xlabel('时间', fontsize=16)
        # 设置 x 坐标轴刻度的旋转方向和大小
        plt.xticks(rotation=90, fontsize=16)
        ax2.grid(True)
        '''
        plt.show()

if __name__ == "__main__":
    cla = PltImage()
    cla.run("000001","2021-01-01","2021-12-01")